package com.ggb.reactive.config

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.ggb.reactive.extension.log
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory
import org.springframework.data.redis.core.ReactiveRedisTemplate
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.RedisSerializationContext
import org.springframework.data.redis.serializer.StringRedisSerializer

@Configuration
class RedisConfig {


    @Bean
    fun reactiveRedisTemplate(
        factory: ReactiveRedisConnectionFactory,
        objectMapper: ObjectMapper
    ): ReactiveRedisTemplate<String, Any> {
        val keySerializer = StringRedisSerializer()
        // redisTemplate序列化java8 时间类Instant报错Java 8 date/time type `java.time.Instant` not supported by default
//        val objectMapper = ObjectMapper()
//        objectMapper.registerModule(JavaTimeModule())

        val valueSerializer = Jackson2JsonRedisSerializer(objectMapper,Any::class.java)


        val builder = RedisSerializationContext.newSerializationContext<String, Any>(keySerializer)
        val context = builder.value(valueSerializer).build()
        log.info("RedisConfig 初始化。。。")

        return ReactiveRedisTemplate(factory, context)
    }


}